package com.chexiehui.jc.ui.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.aries.ui.view.radius.RadiusLinearLayout;
import com.chexiehui.jc.Constants;
import com.chexiehui.jc.R;
import com.chexiehui.jc.base.BaseModel;
import com.chexiehui.jc.base.BaseMvpActivity;
import com.chexiehui.jc.base.BasePage;
import com.chexiehui.jc.entity.BaiDuLocationInfo;
import com.chexiehui.jc.entity.BrandInfo;
import com.chexiehui.jc.entity.CarInfo;
import com.chexiehui.jc.entity.CarSeriesInfo;
import com.chexiehui.jc.entity.DictInfo;
import com.chexiehui.jc.entity.PriceConditionInfo;
import com.chexiehui.jc.mvp.car.StagesBuyCarListCovenant;
import com.chexiehui.jc.mvp.car.StagesBuyCarListPresenter;
import com.chexiehui.jc.utils.BundleBuilder;
import com.chexiehui.jc.utils.GlideUtil;
import com.chexiehui.jc.utils.NoDoubleClickListener;
import com.chexiehui.jc.utils.NoDoubleClickUtils;
import com.chexiehui.jc.widget.CustomAssistantMorePopup;
import com.chexiehui.jc.widget.CustomChooseBrandPopup;
import com.chexiehui.jc.widget.CustomChoosePricePopup;
import com.chexiehui.jc.widget.CustomChooseSortPopup;
import com.chexiehui.jc.widget.CustomInquiryPopup;
import com.chexiehui.jc.widget.LoadingLayout;
import com.lxj.xpopup.XPopup;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.constant.RefreshState;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;
import com.zhy.adapter.recyclerview.CommonAdapter;
import com.zhy.adapter.recyclerview.MultiItemTypeAdapter;
import com.zhy.adapter.recyclerview.base.ViewHolder;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 分期购车列表
 */
public class StagesBuyCarListActivity extends BaseMvpActivity<StagesBuyCarListPresenter> implements StagesBuyCarListCovenant.View{
    @BindView(R.id.ll_head_search)
    RadiusLinearLayout llHeadSearch;
    @BindView(R.id.recycler)
    RecyclerView recycler;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    @BindView(R.id.loadingLayout)
    LoadingLayout loadingLayout;
    @BindView(R.id.tv_choose_sort)
    TextView tvChooseSort;
    @BindView(R.id.rl_choose_sort)
    RelativeLayout rlChooseSort;
    @BindView(R.id.tv_choose_band)
    TextView tvChooseBand;
    @BindView(R.id.rl_choose_band)
    RelativeLayout rlChooseBand;
    @BindView(R.id.tv_choose_down_pay)
    TextView tvChooseDownPay;
    @BindView(R.id.rl_choose_down_pay)
    RelativeLayout rlChooseDownPay;
    @BindView(R.id.tv_choose_month_pay)
    TextView tvChooseMonthPay;
    @BindView(R.id.rl_choose_month_pay)
    RelativeLayout rlChooseMonthPay;
    @BindView(R.id.tv_choose_more)
    TextView tvChooseMore;
    @BindView(R.id.rl_choose_more)
    RelativeLayout rlChooseMore;
    @BindView(R.id.v_split_line)
    View vSplitLine;
    private List<CarInfo> listData;
    private CommonAdapter<CarInfo> listAdapter;
    private BasePage<CarInfo> page;
    private CustomInquiryPopup customInquiryPopup;
    private BaiDuLocationInfo nowCity;
    private CarSeriesInfo tempSeriesInfo;
    private int chooseSortIndex;
    private CustomChooseSortPopup customChooseSortPopup;
    private CustomChooseBrandPopup customChooseBrandPopup;
    private BrandInfo chooseBrand;
    private CustomChoosePricePopup customChooseDownPayPopup;
    private PriceConditionInfo chooseDownPay;
    private CustomChoosePricePopup customChooseMonthPayPopup;
    private PriceConditionInfo chooseMonthPay;
    private PriceConditionInfo choosePrice;
    private DictInfo chooseGrade;
    private DictInfo chooseCountry;
    private List<DictInfo> gradeList;
    private List<DictInfo> countryList;
    private CustomAssistantMorePopup customAssistantMorePopup;

    @Override
    protected void beforeSetView() {
        Bundle bundle = getIntent().getExtras();
        if (bundle != null) {
            nowCity = (BaiDuLocationInfo) bundle.getSerializable("location");
        }
    }

    @Override
    protected void setTitleBar() {
        titleBar.setTitleMainText("分期购车")
                .setDividerVisible(false);
    }

    @Override
    protected int getLayout() {
        return R.layout.activity_stages_buy_car_list;
    }

    @Override
    protected void initView(Bundle var1) {
        llHeadSearch.setOnClickListener(new NoDoubleClickListener() {
            @Override
            public void onNoDoubleClick(View view) {
                startActivity(SearchActivity.class);
            }
        });
        loadingLayout.setStatus(LoadingLayout.Loading);
        refreshLayout.setEnableRefresh(true);
        refreshLayout.setEnableLoadMore(true);
        refreshLayout.setDisableContentWhenLoading(true);
        refreshLayout.setDisableContentWhenRefresh(true);
        refreshLayout.setEnableFooterFollowWhenLoadFinished(false);
        refreshLayout.setEnableLoadMoreWhenContentNotFull(false);
        refreshLayout.setEnableScrollContentWhenRefreshed(true);
        loadingLayout.setOnReloadListener(v -> {
            refreshLayout.finishRefresh(false);
            loadingLayout.setStatus(LoadingLayout.Loading);
            mvpPresenter.getList(1);
        });
        refreshLayout.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                if (loadingLayout.getStatus() == LoadingLayout.Loading) {
                    refreshLayout.finishRefresh(false);
                    return;
                }
                mvpPresenter.getList(1);
            }

            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                if (page != null && page.getTotalRecordCount() > listData.size()) {
                    mvpPresenter.getList(page.getPageIndex() + 1);
                } else {
                    refreshLayout.finishLoadMoreWithNoMoreData();
                }
            }
        });
        recycler.setLayoutManager(new LinearLayoutManager(mContext));
        listData = new ArrayList<>();
        listAdapter = new CommonAdapter<CarInfo>(mContext, R.layout.item_stages_buy_car, listData) {
            @Override
            protected void convert(ViewHolder holder, CarInfo item, int position) {
                GlideUtil.loadImageViewCrop(mContext, item.getImg(), holder.getView(R.id.iv_item_image),
                        R.drawable.shape_square, R.drawable.shape_square);
                holder.setText(R.id.tv_item_name, item.getName());
                holder.setText(R.id.tv_item_first_price, item.getDownPaymentsStr());
                holder.setText(R.id.tv_item_month_price, item.getMonthlyLawStr());
                holder.setOnClickListener(R.id.rtv_item_inquiry, new NoDoubleClickListener() {
                    @Override
                    public void onNoDoubleClick(View view) {
                        showInquiryPopup(item);
                    }
                });
            }
        };
        listAdapter.setOnItemClickListener(new MultiItemTypeAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, RecyclerView.ViewHolder holder, int position) {
                if (NoDoubleClickUtils.isDoubleClick()) return;
                startActivity(CarSeriesDetailsActivity.class,
                        new BundleBuilder().putString("seriesId", listData.get(position).getSeriesId())
                                .create());
            }

            @Override
            public boolean onItemLongClick(View view, RecyclerView.ViewHolder holder, int position) {
                return false;
            }
        });
        recycler.setAdapter(listAdapter);
        mvpPresenter.getCraGradeList();
        mvpPresenter.getCountryTypeList();
        mvpPresenter.getList(1);
    }

    private void showInquiryPopup(CarInfo carInfo) {
        tempSeriesInfo = new CarSeriesInfo();
        tempSeriesInfo.setId(carInfo.getSeriesId());
        if (customInquiryPopup == null) {
            customInquiryPopup = new CustomInquiryPopup(mContext);
            customInquiryPopup.setListener(customInquiryPopupListener);
        }
        customInquiryPopup.initCarModel(carInfo);
        if (nowCity != null) {
            customInquiryPopup.initCity(nowCity);
        }
        new XPopup.Builder(mContext)
                .autoOpenSoftInput(false)
                .autoFocusEditText(false)
                .asCustom(customInquiryPopup)
                .show();
    }

    @Override
    protected StagesBuyCarListPresenter createPresenter() {
        return new StagesBuyCarListPresenter(this);
    }

    @Override
    public void onGetListSuccess(BaseModel<BasePage<CarInfo>> successResult) {
        page = successResult.getData();
        if (loadingLayout.getStatus() != LoadingLayout.Success) {
            loadingLayout.setStatus(LoadingLayout.Success);
        }
        if (refreshLayout.getState() == RefreshState.Refreshing) {
            refreshLayout.finishRefresh();
            listAdapter.getDatas().clear();
            listAdapter.getDatas().addAll(page.getItems());
            listAdapter.notifyDataSetChanged();
        } else if (refreshLayout.getState() == RefreshState.Loading) {
            listAdapter.getDatas().addAll(page.getItems());
            listAdapter.notifyDataSetChanged();
            if (page.getTotalRecordCount() <= listAdapter.getDatas().size()) {
                refreshLayout.finishLoadMoreWithNoMoreData();
            } else {
                refreshLayout.finishLoadMore(true);
            }
        } else {
            refreshLayout.finishRefresh();
            listAdapter.getDatas().clear();
            listAdapter.getDatas().addAll(page.getItems());
            listAdapter.notifyDataSetChanged();
        }
    }

    @Override
    public void onGetListFailure(BaseModel<Object> failureResult) {
        if (Constants.PAGE_DATA_EMPTY == failureResult.getResultCode()) {
            if (refreshLayout.getState() == RefreshState.Refreshing) {
                refreshLayout.finishRefresh(true);
                if (listAdapter.getDatas().size() > 0) {
                    listAdapter.getDatas().clear();
                    listAdapter.notifyDataSetChanged();
                }
                loadingLayout.setStatus(LoadingLayout.Empty);
                loadingLayout.setEmptyText(failureResult.getResultInfo());
            } else if (refreshLayout.getState() == RefreshState.Loading) {
                refreshLayout.finishLoadMoreWithNoMoreData();
            } else {
                loadingLayout.setStatus(LoadingLayout.Empty);
                loadingLayout.setEmptyText(failureResult.getResultInfo());
            }
        } else {
            if (refreshLayout.getState() == RefreshState.Refreshing) {
                refreshLayout.finishRefresh(false);
            }
            if (refreshLayout.getState() == RefreshState.Loading) {
                refreshLayout.finishLoadMore(false);
            }
            if (listAdapter.getDatas().size() <= 0) {
                loadingLayout.setStatus(LoadingLayout.Error);
                loadingLayout.setErrorText(failureResult.getResultInfo());
            } else {
                showToast(failureResult.getResultInfo());
            }
        }
    }

    @Override
    public void onAddShopInquirySuccess(BaseModel<Object> successResult) {
        showLongToast("申请已提交，销售顾问会尽快与您联系！");
        customInquiryPopup.dismiss();
        customInquiryPopup.releaseObj();
        customInquiryPopup = null;
    }

    @Override
    public void onAddShopInquiryFailure(BaseModel<Object> failureResult) {
        showToast(failureResult.getResultInfo());
    }

    @Override
    public void onGetCraGradeListSuccess(BaseModel<List<DictInfo>> successResult) {
        gradeList = successResult.getData();
    }

    @Override
    public void onGetCraGradeListFailure(BaseModel<Object> failureResult) {

    }

    @Override
    public void onGetCountryTypeListSuccess(BaseModel<List<DictInfo>> successResult) {
        countryList = successResult.getData();
    }

    @Override
    public void onGetCountryTypeListFailure(BaseModel<Object> failureResult) {

    }

    @Override
    public String getCityName() {
        return nowCity != null ? nowCity.getCity() : "";
    }

    @Override
    public String getDescStr() {
        return chooseSortIndex == 0 ? "" : chooseSortIndex + "";
    }

    @Override
    public String getBrandId() {
        return chooseBrand != null ? chooseBrand.getId() : "";
    }

    @Override
    public String getSeriesId() {
        return "";
    }

    @Override
    public String getDownPaymentsMin() {
        return chooseDownPay != null ? chooseDownPay.getMin() : "";
    }

    @Override
    public String getDownPaymentsMax() {
        return chooseDownPay != null ? chooseDownPay.getMax() : "";
    }

    @Override
    public String getMonthlyLawMin() {
        return chooseMonthPay != null ? chooseMonthPay.getMin() : "";
    }

    @Override
    public String getMonthlyLawMax() {
        return chooseMonthPay != null ? chooseMonthPay.getMax() : "";
    }

    @Override
    public String getMinPrice() {
        return choosePrice != null ? choosePrice.getMin() : "";
    }

    @Override
    public String getMaxPrice() {
        return choosePrice != null ? choosePrice.getMax() : "";
    }

    @Override
    public String getGradeType() {
        return chooseGrade != null ? chooseGrade.getKey() : "";
    }

    @Override
    public String getCountryType() {
        return chooseCountry != null ? chooseCountry.getKey() : "";
    }

    private CustomInquiryPopup.ICustomInquiryPopupListener customInquiryPopupListener = new CustomInquiryPopup.ICustomInquiryPopupListener() {
        @Override
        public void onInquiryPopupCallChooseModel() {
            startActivityForResult(ChooseCarModelActivity.class, 20,
                    new BundleBuilder().putSerializable("seriesInfo", tempSeriesInfo).create());
        }

        @Override
        public void onInquiryPopupCallChooseCity() {
            startActivityForResult(ChooseCityActivity.class, 21);
        }

        @Override
        public void onInquiryPopupCallChooseMerchant() {
            if (customInquiryPopup != null) {
                if (customInquiryPopup.getChooseModel() == null) {
                    showToast("请选择车型");
                    return;
                }
                if (customInquiryPopup.getChooseCity() == null) {
                    showToast("请选择城市");
                    return;
                }
                startActivityForResult(Shop4sChooseActivity.class, 22,
                        new BundleBuilder()
                                .putSerializable("carId", tempSeriesInfo.getId())
                                .putSerializable("location", customInquiryPopup.getChooseCity())
                                .create());
            }
        }

        @Override
        public void onInquiryPopupApplySubmit(String carid, String shopids, String phone, String name, String city) {
            mvpPresenter.addShopInquiry(carid, shopids, phone, name, city);
        }

        @Override
        public void onInquiryPopupLookAgreement() {
            startActivity(WebActivity.class, new BundleBuilder().putString("url", Constants.YRL_CYHGRXXBHTK).create());
        }
    };

    @OnClick({R.id.rl_choose_sort, R.id.rl_choose_band, R.id.rl_choose_down_pay, R.id.rl_choose_month_pay, R.id.rl_choose_more})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.rl_choose_sort:
                showChooseSortPopup();
                break;
            case R.id.rl_choose_band:
                showChooseBrandPopup();
                break;
            case R.id.rl_choose_down_pay:
                showChooseDownPayPopup();
                break;
            case R.id.rl_choose_month_pay:
                showChooseMonthPayPopup();
                break;
            case R.id.rl_choose_more:
                showChooseMore();
                break;
        }
    }

    private void showChooseMore() {
        if (customAssistantMorePopup == null) {
            customAssistantMorePopup = new CustomAssistantMorePopup(mContext);
            customAssistantMorePopup.setListener(customAssistantMoreListener);
        }
        customAssistantMorePopup.initModel(chooseBrand, choosePrice, chooseGrade, chooseCountry, gradeList, countryList);
        new XPopup.Builder(mContext)
                .hasStatusBarShadow(false)
                .asCustom(customAssistantMorePopup)
                .show();
    }

    private CustomAssistantMorePopup.ICustomAssistantMoreListener customAssistantMoreListener = new CustomAssistantMorePopup.ICustomAssistantMoreListener(){

        @Override
        public void onAssistantMoreChooseBrand() {
            startActivityForResult(ChooseCarModelActivity.class, 30, new BundleBuilder()
                    .putInt("chooseLevel", 1)
                    .create());
        }

        @Override
        public void onAssistantMoreSure(BrandInfo brandInfo, PriceConditionInfo priceInfo, DictInfo gradeInfo, DictInfo countryInfo) {
            chooseBrand = brandInfo;
            choosePrice = priceInfo;
            chooseGrade = gradeInfo;
            chooseCountry = countryInfo;
            if (chooseBrand != null) {
                tvChooseBand.setText(chooseBrand.getName());
            } else {
                tvChooseBand.setText("品牌");
            }
            loadingLayout.setStatus(LoadingLayout.Loading);
            mvpPresenter.getList(1);
        }
    };

    private void showChooseMonthPayPopup() {
        if (customChooseMonthPayPopup == null) {
            List<PriceConditionInfo> priceConditionData = new ArrayList<>();
            priceConditionData.add(new PriceConditionInfo("月供不限", "", ""));
            priceConditionData.add(new PriceConditionInfo("1000以内", "0", "1000"));
            priceConditionData.add(new PriceConditionInfo("1千-2千", "1000", "2000"));
            priceConditionData.add(new PriceConditionInfo("2千-3千", "2000", "3000"));
            priceConditionData.add(new PriceConditionInfo("3千-4千", "3000", "4000"));
            priceConditionData.add(new PriceConditionInfo("4千-5千", "4000", "5000"));
            priceConditionData.add(new PriceConditionInfo("5千以上", "5000", ""));
            customChooseMonthPayPopup = new CustomChoosePricePopup(mContext, priceConditionData);
            customChooseMonthPayPopup.setListener(chooseMonthPayListener);
        }
        customChooseMonthPayPopup.initPriceModel(chooseMonthPay);
        new XPopup.Builder(mContext)
                .atView(vSplitLine)
                .asCustom(customChooseMonthPayPopup)
                .show();
    }

    private CustomChoosePricePopup.ICustomChoosePricePopupListener chooseMonthPayListener = new CustomChoosePricePopup.ICustomChoosePricePopupListener() {
        @Override
        public void onChoosePrice(PriceConditionInfo info) {
            chooseMonthPay = info;
            tvChooseMonthPay.setText(info.getName());
            loadingLayout.setStatus(LoadingLayout.Loading);
            mvpPresenter.getList(1);
        }
    };

    private void showChooseDownPayPopup() {
        if (customChooseDownPayPopup == null) {
            List<PriceConditionInfo> priceConditionData = new ArrayList<>();
            priceConditionData.add(new PriceConditionInfo("首付不限", "", ""));
            priceConditionData.add(new PriceConditionInfo("5000以内", "0", "0.5"));
            priceConditionData.add(new PriceConditionInfo("0.5-1万", "0.5", "1"));
            priceConditionData.add(new PriceConditionInfo("1-2万", "1", "2"));
            priceConditionData.add(new PriceConditionInfo("2-3万", "2", "3"));
            priceConditionData.add(new PriceConditionInfo("4-5万", "4", "5"));
            priceConditionData.add(new PriceConditionInfo("5万以上", "5", ""));
            customChooseDownPayPopup = new CustomChoosePricePopup(mContext, priceConditionData);
            customChooseDownPayPopup.setListener(chooseDownPayListener);
        }
        customChooseDownPayPopup.initPriceModel(chooseDownPay);
        new XPopup.Builder(mContext)
                .atView(vSplitLine)
                .asCustom(customChooseDownPayPopup)
                .show();
    }

    private CustomChoosePricePopup.ICustomChoosePricePopupListener chooseDownPayListener = new CustomChoosePricePopup.ICustomChoosePricePopupListener() {
        @Override
        public void onChoosePrice(PriceConditionInfo info) {
            chooseDownPay = info;
            tvChooseDownPay.setText(info.getName());
            loadingLayout.setStatus(LoadingLayout.Loading);
            mvpPresenter.getList(1);
        }
    };

    private void showChooseBrandPopup() {
        if (customChooseBrandPopup == null) {
            customChooseBrandPopup = new CustomChooseBrandPopup(mContext);
            customChooseBrandPopup.setListener(customChooseBrandPopupListener);
        }
        customChooseBrandPopup.initBrandModel(chooseBrand);
        new XPopup.Builder(mContext)
                .atView(vSplitLine)
                .asCustom(customChooseBrandPopup)
                .show();
    }

    private CustomChooseBrandPopup.ICustomChooseBrandPopupListener customChooseBrandPopupListener = new CustomChooseBrandPopup.ICustomChooseBrandPopupListener() {
        @Override
        public void onRemoveBrand() {
            chooseBrand = null;
            tvChooseBand.setText("品牌");
            loadingLayout.setStatus(LoadingLayout.Loading);
            mvpPresenter.getList(1);
        }

        @Override
        public void onChooseBrand() {
            startActivityForResult(ChooseCarModelActivity.class, 20, new BundleBuilder()
                    .putInt("chooseLevel", 1)
                    .create());
        }
    };

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case 20:
                if (resultCode == RESULT_OK) {
                    if (data != null) {
                        BrandInfo brandInfo = (BrandInfo) data.getSerializableExtra("brandInfo");
                        if (brandInfo != null) {
                            if (chooseBrand != null && chooseBrand.getId().equals(brandInfo.getId())) {
                                return;
                            }
                            chooseBrand = brandInfo;
                            tvChooseBand.setText(brandInfo.getName());
                            loadingLayout.setStatus(LoadingLayout.Loading);
                            mvpPresenter.getList(1);
                        }
                    }
                }
                break;
            case 30:
                if (resultCode == RESULT_OK) {
                    if (data != null) {
                        BrandInfo brandInfo = (BrandInfo) data.getSerializableExtra("brandInfo");
                        if (brandInfo != null) {
                            customAssistantMorePopup.notifyBrandInfo(brandInfo);
                        }
                    }
                }
                break;
        }
    }

    private void showChooseSortPopup() {
        if (customChooseSortPopup == null) {
            customChooseSortPopup = new CustomChooseSortPopup(mContext);
            customChooseSortPopup.setListener(customChooseSortPopupListener);
        }
        new XPopup.Builder(mContext)
                .atView(vSplitLine)
                .asCustom(customChooseSortPopup)
                .show();
    }

    private CustomChooseSortPopup.ICustomChooseSortPopupListener customChooseSortPopupListener = new CustomChooseSortPopup.ICustomChooseSortPopupListener() {
        @Override
        public void onChooseSort(int position, String name) {
            chooseSortIndex = position;
            tvChooseSort.setText(name);
            loadingLayout.setStatus(LoadingLayout.Loading);
            mvpPresenter.getList(1);
        }
    };

}
